import socketio

from role.admin import Admin


sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins=[])


@sio.event
async def connect(sid, environ):
    # 连接成功之后,会自动恢复一个connect事件给前端
    print(f'~~~~sid={sid}, {environ["HTTP_ORIGIN"]},连接成功~~~~')
    sio.enter_room(sid, "agv")

    if not Admin().get_admint():
        # 默认连接的都是设置admin
        Admin().set_admin(sid)
        print('控制者——————————————————————————————————')
        await sio.emit('seizecontrol', True, to=sid)
    else:
        pass
    await sio.emit("message", f"sid={sid},进入房间", room="agv")


@sio.event
async def disconnect(sid):
    # 连接成功之后,会自动恢复一个connect事件给前端
    print(f"~~~~sid={sid},断开连接~~~~")
    sio.leave_room(sid, "agv")
    Admin().release_admin(sid)
    await sio.emit("disconnect", f"sid={sid},离开房间", room="agv")


@sio.event
async def message(sid, data):
    # 连接成功之后,会自动恢复一个connect事件给前端
    print(f"~~~~data= {data}, message from sid ={sid}~~~~")
    await sio.emit("message", "msg from server", room="agv")
    print(sio.rooms(sid))
